<template>
  <el-tree
    class="tree"
    :data="dataSource"
    show-checkbox
    node-key="id"
    default-expand-all
    :expand-on-click-node="false"
    :default-checked-keys="defaultCheckedKeys"
    :checked-keys="permissionIds"
    @check="handleCheck"
  >
    <template #default="{ node, data }">
      <div class="custom-tree-node">
        <span>{{ node.label }}</span>
        <div v-if="!readOnly">
          <!-- <el-button type="primary" link @click="editPoint(data)">
            编辑
          </el-button> -->
          <el-button type="primary" link @click="addSiblingPoint(data)">
            新增同级
          </el-button>
          <el-button
            type="primary"
            link
            @click="addSubPoint(data)"
            v-if="platformId == 1 || platformId == 2"
          >
            新增下级
          </el-button>
          <el-button
            style="margin-left: 4px"
            type="danger"
            link
            @click="deletePoint(node, data)"
          >
            删除
          </el-button>
        </div>
      </div>
    </template>
    <template #empty>
      <el-button type="primary" link @click="append(data)">
        新增权限点
      </el-button>
    </template>
  </el-tree>

  <!-- 新增权限点弹窗 -->
  <el-dialog v-model="dialogVisible" title="新增权限点" width="50%">
    <el-form :model="form" label-width="120px" label-position="top">
      <template v-if="platformId == 1 || platformId == 2">
        <el-form-item label="权限点名称">
          <el-input v-model="form.permissionName" />
        </el-form-item>
        <el-form-item label="权限点标识">
          <el-input v-model="form.permissionSign" />
        </el-form-item>
        <el-form-item label="权限类型">
          <el-select v-model="form.permissionType" placeholder="请选择">
            <el-option label="页面" :value="1" />
            <el-option label="功能点" :value="2" />
            <el-option label="数据" :value="3" />
          </el-select>
        </el-form-item>
      </template>
      <template v-if="platformId == 3">
        <!-- 地址系统 -->
        <el-form-item label="地址系统">
          <el-select v-model="form.addressId" placeholder="请选择">
            <el-option
              v-for="item in addressList"
              :key="item.id"
              :label="item.addressName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </template>
      <!-- 课程系统 -->
      <template v-if="platformId == 4">
        <el-form-item label="课程系统">
          <el-select v-model="form.courseId" placeholder="请选择">
            <el-option
              v-for="item in courseList"
              :key="item.id"
              :label="item.courseName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addPermissionPoint"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from "vue";
import {
  addPermissionPointRequest,
  deletePermissionPointRequest,
} from "@/apis/permission.js";

const dataSource = ref([]);

const props = defineProps({
  // 新增/编辑
  optionType: {
    type: String,
    default: "add",
  },
  //权限类型 1-管理系统；2-小程序（H5）；3-场地数据；4-课程数据
  platformId: {
    type: String,
    default: 3,
  },
  // 权限点列表
  dataSource: {
    type: Array,
    default: [],
  },
  // 权限包id
  permissionPackageId: {
    type: String,
    default: "",
  },
  // 选中的权限点id数组
  permissionIds: {
    type: Array,
    default: () => [],
  },
  // 地址列表
  addressList: {
    type: Array,
    default: () => [],
  },
  // 课程列表
  courseList: {
    type: Array,
    default: () => [],
  },
  // 更新数据
  updateData: {
    type: Function,
    default: () => {},
  },
});

const emit = defineEmits(["update:permission-ids"]);

watch(
  () => props.dataSource,
  (newVal) => {
    console.log(newVal);
    dataSource.value = newVal;
  },
  {
    immediate: true,
  }
);

const defaultCheckedKeys = ref([]);

watch(
  () => props.permissionIds,
  (newVal) => {
    defaultCheckedKeys.value = newVal;
    console.log(defaultCheckedKeys.value, "permissionIds");
  }
);

const readOnly = computed(() => {
  return (
    props.optionType === "look" ||
    props.platformId === "3" ||
    props.platformId === "4"
  );
});
const dialogVisible = ref(false);
const form = ref({});
const formInit = () => {
  form.value = Object.assign(
    {
      platformId: props.platformId,
      permissionName: "",
      permissionSign: "",
      parentId: "0",
      permissionType: [3, 4].includes(props.platformId) ? 3 : "",
    },
    props.platformId == 3
      ? { addressId: "" }
      : props.platformId == 4
      ? { courseId: "" }
      : {}
  );

  console.log(form.value, 1132);
};
formInit();
// 新增同级权限点
const addSiblingPoint = (data) => {
  dialogVisible.value = true;
  form.value.parentId = data.parentId || 0;
};

// 编辑权限点
const editPoint = (data) => {
  dialogVisible.value = true;
  form.value.id = data.id;
  form.value.permissionName = data.permissionName;
  form.value.permissionSign = data.permissionSign;
  form.value.permissionType = data.permissionType;
};

// 新增下级权限点
const addSubPoint = (data) => {
  dialogVisible.value = true;
  form.value.parentId = data.id;
};

// 确定-新增权限点
const addPermissionPoint = async () => {
  const res = await addPermissionPointRequest(form.value);
  if (res.code === "00000") {
    dialogVisible.value = false;
    props.updateData();
    formInit();
  } else {
    ElMessage.error(res.message);
  }
};

// 删除权限点
const deletePoint = async (node, data) => {
  const res = await deletePermissionPointRequest({ id: data.id });
  if (res.code === "00000") {
    ElMessage.success("删除成功");
    props.updateData && props.updateData();
  } else {
    ElMessage.error(res.message);
  }
};

watch(
  () => form.value.courseId,
  (newVal) => {
    form.value.permissionName = props.courseList.find(
      (item) => item.id === newVal
    )?.courseName;
    form.value.permissionSign = props.courseList.find(
      (item) => item.id === newVal
    )?.id;
  }
);

watch(
  () => form.value.addressId,
  (newVal) => {
    form.value.permissionName = props.addressList.find(
      (item) => item.id === newVal
    )?.addressName;
    form.value.permissionSign = props.addressList.find(
      (item) => item.id === newVal
    )?.id;
  }
);
// 处理选中状态变化
const handleCheck = (data, checked) => {
  console.log(checked.checkedKeys);
  emit("update:permission-ids", checked.checkedKeys);
};
</script>

<style lang="less" scoped>
.tree {
  width: 100%;
  max-width: 600px;
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
}
</style>
